package repositories

import (
	"context"
	"errors"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"nodeseller/datamodels"
	mymongo "nodeseller/mongo"
)

type IStore interface {
	//连接数据库
	Conn()(error)
	//插入数据库
	Insert(user *datamodels.Store)(error)
	//删除数据库
	Delete(primitive.ObjectID)bool
	//查所有店铺
	SelectByKey(phonenumber string)([]datamodels.Store,error)
}
type StoreManager struct {
	mongoDataColletion mymongo.Collection
}
func NewStoreManager()IStore  {
	mongodb,err := mymongo.Get()
	if err != nil{
		return nil
	}
	return &StoreManager {
		mongodb.Collection("store"),
	}
}
//数据库连接
func (p *StoreManager)Conn()(err error)  {
	if p.mongoDataColletion == nil{
		mongodb,err := mymongo.Get()
		if err != nil{
			return err
		}
		p.mongoDataColletion = mongodb.Collection("store")
	}
	return nil
}
//插入数据库
func (p *StoreManager)Insert(user *datamodels.Store)(error)  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return  err
	}
	insertresult,err := p.mongoDataColletion.InsertOne(context.TODO(),user)
	if err != nil{
		return err
	}
	if insertresult.InsertedID != nil{
		return nil
	}else{
		return errors.New("加入数据库错误")
	}
}
//删除店铺
func (p *StoreManager)Delete(storeid primitive.ObjectID)bool  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return  false
	}
	updateresult,err := p.mongoDataColletion.UpdateOne(context.TODO(),bson.M{"_id":storeid},bson.M{"delete":false})
	if err != nil{
		return false
	}
	if updateresult.ModifiedCount > 0{
		return true
	}
	return false
}
//查看自己所有店铺
func (p *StoreManager)SelectByKey(phonenumber string)(result []datamodels.Store,err error)  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return result,err
	}
	cur,err := p.mongoDataColletion.Find(context.TODO(),bson.M{"phonenumber":phonenumber,"delete":false})
	if err != nil{
		return result,err
	}
	for cur.Next(context.TODO()){
		//创建一个值，将单个文档解码为该值
		var elem datamodels.Store
		err := cur.Decode(&elem)
		if err != nil{
			fmt.Println(err)
			return result,err
		}
		result = append(result,elem)
	}
	return result,nil
}